package com.iqilu.ksd.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.andview.refreshview.XRefreshView;
import com.andview.refreshview.XRefreshViewFooter;
import com.google.gson.reflect.TypeToken;
import com.iqilu.ksd.R;
import com.iqilu.ksd.adapter.NewsAdapter;
import com.iqilu.ksd.adapter.SearchAdapter;
import com.iqilu.ksd.bean.MessageBean;
import com.iqilu.ksd.bean.NewsItemBean;
import com.iqilu.ksd.constant.Api;
import com.iqilu.ksd.constant.Config;
import com.iqilu.ksd.constant.NewsType;
import com.iqilu.ksd.utils.JSONUtils;
import com.iqilu.ksd.utils.KeyboardUtils;
import com.jaeger.library.StatusBarUtil;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.ArrayList;

import okhttp3.Call;
import okhttp3.Request;

/**
 * Created by Coofee on 2017/1/16.
 */

public class SearchActivity extends BaseActivity {

    private static final String TAG = "SearchActivity";

    private int page = 1;
    private ArrayList<NewsItemBean> list;
    private SearchAdapter adapter;

    private ImageView btLeft;
    private TextView tvTitle;
    private XRefreshView xRefreshView;
    private RecyclerView rvList;
    private EditText etTitle;
    private Button btSearch;
    private ImageView imgEmpty;
    private RelativeLayout layLoading;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        StatusBarUtil.setColor(this, ContextCompat.getColor(this, R.color.blue_dark), Config.STATUSBAR_ALPHA);
        initView();
        adapter = new SearchAdapter(this);
        adapter.setCustomLoadMoreView(new XRefreshViewFooter(this));
        adapter.setOnItemClickListener(onItemClickListener);
        rvList.setAdapter(adapter);
        xRefreshView.setPullRefreshEnable(false);
        xRefreshView.setPullLoadEnable(true);
        xRefreshView.setMoveForHorizontal(true);
        xRefreshView.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener() {
            @Override
            public void onRefresh() {
                super.onRefresh();
                page = 1;
                getList();
            }

            @Override
            public void onLoadMore(boolean isSilence) {
                super.onLoadMore(isSilence);
                page++;
                getList();
            }
        });
    }

    private void initView() {
        btLeft = getView(R.id.bt_left);
        tvTitle = getView(R.id.tv_title);
        xRefreshView = getView(R.id.xRefreshView);
        rvList = getView(R.id.rv_list);
        etTitle = getView(R.id.et_title);
        btSearch = getView(R.id.bt_search);
        imgEmpty = getView(R.id.img_empty);
        layLoading = getView(R.id.lay_loading);
        btSearch.setClickable(false);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(OrientationHelper.VERTICAL);
        rvList.setLayoutManager(layoutManager);

        etTitle.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(etTitle.getText().toString())) {
                    btSearch.setClickable(false);
                    btSearch.setTextColor(ContextCompat.getColor(SearchActivity.this, R.color.search_bt_not));
                } else {
                    btSearch.setClickable(true);
                    btSearch.setTextColor(Color.WHITE);
                }
            }
        });

        btSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!TextUtils.isEmpty(etTitle.getText().toString())) {
                    page = 1;
                    imgEmpty.setVisibility(View.GONE);
                    layLoading.setVisibility(View.VISIBLE);
                    KeyboardUtils.hideSoftInput(SearchActivity.this);
                    getList();
                }
            }
        });

        btLeft.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private void getList() {
        String keyword = etTitle.getText().toString();
        String url = Api.URL_ARTICLE_SEARCH + "?keyword=" + keyword + "&page=" + page;
        Log.i(TAG, "url=" + url);
        OkHttpUtils.get().url(url).tag(this).build().execute(new StringCallback() {

            @Override
            public void onBefore(Request request, int id) {
                super.onBefore(request, id);
                if (list == null || page == 1) {
                    list = new ArrayList<NewsItemBean>();
                }
                if (xRefreshView.getVisibility() == View.GONE) {
                    xRefreshView.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onError(Call call, Exception e, int id) {
                afterRefresh();
                Toast.makeText(SearchActivity.this, R.string.load_error, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(String response, int id) {
                afterRefresh();
                ArrayList<NewsItemBean> result = JSONUtils.requestList(response, "data", new TypeToken<ArrayList<NewsItemBean>>() {
                });
                if (page == 1) {
                    if (result == null || result.size() == 0) {
                        imgEmpty.setVisibility(View.VISIBLE);
                        xRefreshView.setVisibility(View.GONE);
                        Toast.makeText(SearchActivity.this, R.string.search_empty, Toast.LENGTH_SHORT).show();
                    } else {
                        list = result;
                    }
                    adapter.setData(list);
                    adapter.notifyDataSetChanged();
                } else {
                    if (result == null || result.size() == 0) {
                        Toast.makeText(SearchActivity.this, R.string.no_more, Toast.LENGTH_SHORT).show();
                    } else {
                        list.addAll(result);
                        adapter.setData(list);
                        adapter.notifyDataSetChanged();
                    }
                }
            }
        });
    }

    private void afterRefresh() {
        imgEmpty.setVisibility(View.GONE);
        layLoading.setVisibility(View.GONE);
        if (page == 1) {
            xRefreshView.stopRefresh();
        } else {
            xRefreshView.stopLoadMore();
        }
    }

    private NewsAdapter.OnItemClickListener onItemClickListener = new NewsAdapter.OnItemClickListener() {
        @Override
        public void OnItemClickListener(View view, int position) {
            Intent intent = null;
            NewsItemBean item = list.get(position);
            if (item.getType().equals(NewsType.HEAD)) {
                item.setType(item.getRealtype());
            }
            if (item.getType().equals(NewsType.ARTICLE)) {
                intent = new Intent(SearchActivity.this, NewsDetailActivity.class);
                intent.putExtra("id", item.getId());
                intent.putExtra("catId", item.getCatid());
            } else if (item.getType().equals(NewsType.GALLERY) || item.getType().equals(NewsType.PHOTO)) {
                intent = new Intent(SearchActivity.this, GalleryActivity.class);
                intent.putExtra("id", item.getId());
                intent.putExtra("catId", item.getCatid());
                intent.putExtra("position", 0);
            } else if (item.getType().equals(NewsType.AD) || item.getType().equals(NewsType.URL)) {
                intent = new Intent(SearchActivity.this, ADActivity.class);
                intent.putExtra("title", item.getTitle());
                intent.putExtra("type", item.getType());
                intent.putExtra("adUrl", item.getUrl());
                if (item.getType().equals(NewsType.AD)) {
                    intent.putExtra("shareicon", item.getShareicon());
                } else {
                    intent.putExtra("thumb", item.getThumb());
                }
            } else if (item.getType().equals(NewsType.LIVE)) {
                intent = new Intent(SearchActivity.this, LiveActivity.class);
                intent.putExtra("id", item.getId());
            } else if (item.getType().equals(NewsType.CLUE)) {
                intent = new Intent(SearchActivity.this, PaikeActivity.class);
                intent.putExtra("id", item.getId());
            }
            if (intent != null) {
                startActivity(intent);
            }
        }
    };
}
